// src/store/index.js
import { createStore } from 'vuex'

// 从 localStorage 获取用户信息和地址
const savedUserInfo = localStorage.getItem('userInfo') || null
const savedAddress = localStorage.getItem('address') || ''
const savedOrders = JSON.parse(localStorage.getItem('orders')) || [] // 修改为订单数组

export default createStore({
  state() {
    return {
      user: savedUserInfo ? JSON.parse(savedUserInfo) : {
        username: null,
        password: null,
        position: null
      },
      address: savedAddress,
      orders: savedOrders, // 修改为 orders 数组
      currentOrder: null, // 添加当前订单状态
      // 添加管理员订单列表状态
      adminOrders: []
    }
  },
  mutations: {
    SET_USER_INFO(state, { username, password, position }) {
      state.user = { username, password, position }
      localStorage.setItem('userInfo', JSON.stringify(state.user))
    },
    CLEAR_USER_INFO(state) {
      state.user = {
        username: null,
        password: null,
        position: null
      }
      localStorage.removeItem('userInfo')
    },
    SET_ADDRESS(state, address) {
      state.address = address
      localStorage.setItem('address', address)
    },
    CLEAR_ADDRESS(state) {
      state.address = ''
      localStorage.removeItem('address')
    },
    // 修改订单相关的 mutations
    ADD_ORDER(state, order) {
      state.orders.push(order)
      localStorage.setItem('orders', JSON.stringify(state.orders))
    },
    CLEAR_ORDERS(state) {
      state.orders = []
      localStorage.removeItem('orders')
    },
    // 添加当前订单相关的 mutations
    SET_CURRENT_ORDER(state, order) {
      state.currentOrder = order
    },
    // 管理员订单列表相关 mutations
    SET_ADMIN_ORDERS(state, orders) {
      state.adminOrders = orders
    },
    ADD_ADMIN_ORDER(state, order) {
      // 检查订单是否已存在
      const exists = state.adminOrders.some(o => o.id === order.id)
      if (!exists) {
        state.adminOrders.push(order)
      }
    },
    // 添加移除订单的 mutations
    REMOVE_ORDER(state, orderId) {
      // 从用户订单中移除
      state.orders = state.orders.filter(order => order.id !== orderId)
      // 从管理员订单中移除
      state.adminOrders = state.adminOrders.filter(order => order.id !== orderId)
      // 清除当前订单
      if (state.currentOrder && state.currentOrder.id === orderId) {
        state.currentOrder = null
      }
      // 更新 localStorage
      localStorage.setItem('orders', JSON.stringify(state.orders))
    }
  },
  actions: {
    saveUserInfo({ commit }, userInfo) {
      commit('SET_USER_INFO', userInfo)
    },
    clearUserInfo({ commit }) {
      commit('CLEAR_USER_INFO')
    },
    saveAddress({ commit }, address) {
      commit('SET_ADDRESS', address)
    },
    clearAddress({ commit }) {
      commit('CLEAR_ADDRESS')
    },
    // 修改订单相关的 actions
    saveOrder({ commit }, order) {
      commit('ADD_ORDER', order)
      // 同时添加到管理员订单列表
      commit('ADD_ADMIN_ORDER', order)
    },
    clearOrders({ commit }) {
      commit('CLEAR_ORDERS')
    },
    // 管理员订单列表相关 actions
    loadAdminOrders({ commit }) {
      // 从 localStorage 获取所有订单（实际项目中应从服务器获取）
      const orders = []
      const savedOrders = JSON.parse(localStorage.getItem('orders')) || []
      orders.push(...savedOrders)
      commit('SET_ADMIN_ORDERS', orders)
    },
    setAdminOrders({ commit }, orders) {
      commit('SET_ADMIN_ORDERS', orders)
    },
    // 移除订单的 action
    removeOrder({ commit }, orderId) {
      commit('REMOVE_ORDER', orderId)
    }
  },
  getters: {
    getUserInfo: state => state.user,
    cartItems: state => {
      // 根据当前用户获取购物车项目
      if (!state.user.username) return []
      const userCartKey = `cart_${state.user.username}`
      return JSON.parse(localStorage.getItem(userCartKey) || '[]')
    },
    cartTotal: state => {
      // 根据当前用户计算购物车总金额
      if (!state.user.username) return 0
      const userCartKey = `cart_${state.user.username}`
      const cart = JSON.parse(localStorage.getItem(userCartKey) || '[]')
      return cart.reduce((total, item) => total + (item.gPrice * item.quantity), 0)
    },
    cartItemCount: state => {
      // 根据当前用户计算购物车商品总数
      if (!state.user.username) return 0
      const userCartKey = `cart_${state.user.username}`
      const cart = JSON.parse(localStorage.getItem(userCartKey) || '[]')
      return cart.reduce((count, item) => count + item.quantity, 0)
    },
    getAddress: state => state.address,
    // 修改订单相关的 getters
    getOrders: state => state.orders,
    getOrder: state => state.orders.length > 0 ? state.orders[state.orders.length - 1] : null, // 获取最新订单
    getCurrentOrder: state => state.currentOrder, // 获取当前订单
    // 管理员订单列表相关 getters
    getAdminOrders: state => state.adminOrders
  }
})